import React, { useState, useEffect, useImperativeHandle } from 'react';
import { connect } from 'react-redux';
import { actions as echartsActions } from '@/redux/echartsList';
import { actions as singleTempActions } from '@/redux/singleTemp';
import { actions as publicTempActions } from '@/redux/publicTemp';
import { Input, Skeleton, message } from 'antd';
// eslint-disable-next-line no-unused-vars
import { fuzzyQueryTemp, getTempDetail } from '@/api/index';
import { Icon } from 'antd';
import _ from 'lodash';
const { Search } = Input;
// eslint-disable-next-line complexity
const Panel = ({
  setTempData,
  pageNo,
  setTags,
  setFormInfo,
  setIsShare,
  tags,
  handleCurIndex,
  curIndex,
  cRef,
  queryEchartList,
  isShowEcharts,
  echartsList,
  querySingleTempList,
  singleTempList,
  isShowSingleTemp,
  queryPublicTempList,
  isShowPublicTemp,
  publicTempList,
  filterSingleTempList,
  filterPublicTempList,
}) => {
  const [visible1, setVisible1] = useState(false);
  const [visible2, setVisible2] = useState(false);
  const [visible3, setVisible3] = useState(false);
  const [visible4, setVisible4] = useState(false);
  const [visible5, setVisible5] = useState(false);

  const addTag = tag => {
    const fi = _.findIndex(tags, o => o.cucId === tag.cucId);
    handleCurIndex(tag.cucId);
    if (fi < 0) {
      const t = _.clone(tags);
      t.push(tag);
      setTags(t);
    }
  };
  const isExistCurIndex = (tags, curIndex) => {
    return tags.some(ele => {
      return curIndex === ele.cucId;
    });
  };

  const handleTempListClicked = (tempId, pageNo) => {

    getTempDetail(tempId, pageNo).then(res => {
      if (res.code === '0') {
        res.data.list.forEach(e => {
          e.cfiConfigId = e.cfiId;
        });
        setFormInfo(_.clone(res.data.list));
      } else {
        message.error(res.msg);
      }
    });
  };

  useImperativeHandle(cRef, () => ({
    // changeVal 就是暴露给父组件的方法
    changeVal: () => {
      // 父组件调用子组件的 changeVal 保存模板配置
      querySingleTempList();
    },
    changePublic: () => {
      queryPublicTempList();
    }
  }));

  useEffect(() => {

    // 查询左下角 echarts 图标
    queryEchartList();

    // 个人模板
    querySingleTempList();

    // 公共模板
    queryPublicTempList();

  }, []);

  return (
    <div className="panel-box" >
      <div className="panel-box-item" style={{ height: '40%', overflow: 'auto' }}>
        <div className="btn" onClick={() => setVisible1(!visible1)}>
          <span>工作台模板</span>
          <img src={require('../../assets/images/open.png')} alt="" />
        </div>
        <div className="content" style={{ paddingTop: visible1 ? 0 : '10px', maxHeight: visible1 ? 0 : '1000px' }}>
          <Search placeholder="请输入模板名称" onSearch={value => {
            // search
            filterSingleTempList(value);
            filterPublicTempList(value);
          }} />
          <div className="group-btn" onClick={() => setVisible2(!visible2)}>
            公共模板
            <span className="group-btn-iconbox">
              <img src={require('../../assets/images/openselect.png')} alt="" />
            </span>
          </div>
          <ul className="group-list" style={{ paddingBottom: visible2 ? 0 : '10px', maxHeight: visible2 ? 0 : '1000px' }}>
            <Skeleton title={false} loading={isShowPublicTemp} active>
              {
                // eslint-disable-next-line complexity
                publicTempList.map((tag, index) => (
                  <li key={index} className={curIndex === tag.cucId ? 'active-tag-views' : ''} onClick={
                    () => {
                      setIsShare(tag.cucIsShare);
                      addTag(tag);
                      handleTempListClicked(tag.cucId, pageNo);
                    }
                  }>{tag.cucName}</li>
                ))
              }
            </Skeleton>
          </ul>

          <div className="group-btn" onClick={() => setVisible3(!visible3)}>个人模板<span className="group-btn-iconbox"><img src={require('../../assets/images/openselect.png')} alt="" /></span></div>
          <ul className="group-list" style={{ paddingBottom: visible3 ? 0 : '10px', maxHeight: visible3 ? 0 : '1000px' }}>
            <Skeleton style={{ width: '100%' }} key={1} title={false} loading={isShowSingleTemp} active>
              {
                // eslint-disable-next-line complexity
                singleTempList.map((tag, index) => (
                  <li key={tag.cucId} className={curIndex === tag.cucId ? 'active-tag-views' : ''} onClick={
                    () => {
                      setIsShare(tag.cucIsShare);
                      addTag(tag);
                      handleTempListClicked(tag.cucId, pageNo);
                    }
                  }>{tag.cucName}{tag.cucStatus === '1' ? '（编辑中）' : (tag.cucStatus === '2' ? '（保存）' : '（发布）')}</li>
                ))
              }
            </Skeleton>
          </ul>

        </div>
      </div>
      <img style={{ margin: '10px 0' }} src={require('../../assets/images/l-panel.png')} alt="" />
      <div className="panel-box-item" style={{ height: '57%', overflow: 'auto' }}>
        <div className="btn" onClick={() => setVisible4(!visible4)}>应用套件<img src={require('../../assets/images/open.png')} alt="" /></div>
        <div className="content" style={{ paddingTop: visible4 ? 0 : '10px', maxHeight: visible4 ? 0 : '1000px' }}>
          <div className="temp-btn" onClick={() => setVisible5(!visible5)}>
            <span>图表类型</span>
            <span className="temp-btn-iconbox">
              <Icon type="caret-down" />
            </span>
          </div>
          <ul className="temp-list" style={{ maxHeight: visible5 ? 0 : '1000px' }}>
            {
              echartsList.map((item, index) => (
                <Skeleton key={index} title={false} loading={isShowEcharts} active>
                  <li key={index} draggable="true" onDragOver={e => e.preventDefault()} onDragStart={() => {
                    if (!isExistCurIndex(tags, curIndex)) {
                      message.warning('请先选择模板');
                    } else {
                      item.pageNo = JSON.stringify(pageNo);
                      setTempData(item);
                    }
                  }} unselectable="on" >
                    <img src={require('../../assets/images/tempIcons/' + item.type + '.png')} alt="" />
                    <div className="title">{item.name}</div>
                  </li>
                </Skeleton>
              ))
            }
          </ul>
        </div>
      </div>
    </div>
  );
};

const mapStateToProps = ({ echartsListState, singleTemp, publicTemp }) => {
  const { isShowEcharts, echartsList } = echartsListState;
  const { isShowSingleTemp, singleTempList } = singleTemp;
  const { isShowPublicTemp, publicTempList } = publicTemp;

  return {
    isShowEcharts,
    isShowSingleTemp,
    isShowPublicTemp,
    echartsList,
    singleTempList,
    publicTempList
  };
};

const mapDispatchToProps = dispatch => {
  return {
    queryEchartList: () => dispatch(echartsActions.fetchData()),
    querySingleTempList: () => dispatch(singleTempActions.fetchData()),
    queryPublicTempList: () => dispatch(publicTempActions.fetchData()),
    filterSingleTempList: value => dispatch(singleTempActions.filterList(value)),
    filterPublicTempList: value => dispatch(publicTempActions.filterList(value))
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Panel);
